﻿using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Action007_反转整数
    {
        public int Reverse1(int x)
        {
            //1. 栈反转
            bool isNeg = x < 0;
            if (isNeg)
            {
                x = -x;
            }

            Stack<int> stack = new Stack<int>();

            while (x != 0)
            {
                int m = x % 10;
                stack.Push(m);
                x = x / 10;
            }

            int ten = 1;
            int count = stack.Count;
            for (int i = 0; i < count; i++)
            {
                int pop = stack.Pop()*ten;
                ten = ten * 10;

                try
                {
                    x += pop;
                }
                catch (Exception)
                {
                    return 0;
                }
            }

            if (isNeg)
            {
                x = -x;
            }
            return x;
        }

        public void Test()
        {
            Console.WriteLine(Reverse(123));
            Console.WriteLine(Reverse(-123));
            Console.WriteLine(Reverse(123456789));
            Console.WriteLine(Reverse(1234567899));
            Console.WriteLine(Reverse(-1234567899));
        }
        public int Reverse(int x)
        {
            /*重复“弹出” x 的最后一位数字，并将它“推入”到 rev 的后面。
             最后，rev 将与 x 相反。   */
            int rev = 0;

            while (x != 0)
            {
                int pop = x % 10;
                x /= 10;

                //溢出验证
                //rev = temp = rev * 10 + pop
                // 要求  MIN <= rev * 10 + pop <= MAX
                // 即要求 rev <= (MAX - pop)/10 && rev>= (MIN-pop)/10
                // 即rev <= MAX/10 && rev>=MIN/10
                if (rev > int.MaxValue/10 || rev < int.MinValue/10 )
                {
                    return 0;
                }

                rev = rev * 10 + pop;
            }

            return rev;
        }
    }
}
